import React, { Component } from 'react';
import { Button, Modal, Select, Form, Row, Col, Input, Radio, DatePicker, message } from 'antd';
import { connect } from 'dva';
import BaseComponent from '@/components/BaseComponent';
import moment from 'moment';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
@Form.create()
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      form: {},
      allTableData: [],
      provinceIdData: [],
      cityIdData: [],
      districtIdData: [],
      townshipIdData: [],
      villageIdData: [],
      whether: [
        { label: '未随访', value: 1 },
        { label: '已随访', value: 2 },
      ],
    };
  }

  provinceIdChange = value => {
    const str = value ? this.state.provinceIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          provinceId: value,
          provinceName: name,
        },
      }),
      () => {
        this.getCity({ level: 2, parentCode: value });
      }
    );
  };
  cityIdChange = value => {
    const str = value ? this.state.cityIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
          cityName: name,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  districtIdChange = value => {
    const str = value ? this.state.districtIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          districtId: value,
          districtName: name,
        },
      }),
      () => {
        this.getCity({ level: 4, parentCode: value });
      }
    );
  };
  townshipIdChange = value => {
    const str = value ? this.state.townshipIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          townshipId: value,
          townshipName: name,
        },
      }),
      () => {
        this.getCity({ level: 5, parentCode: value });
      }
    );
  };

  villageIdChange = value => {
    const str = value ? this.state.villageIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(params => ({
      form: {
        ...params.form,
        villageId: value,
        villageName: name,
      },
    }));
  };

  nameChange = value => {
    const item = this.state.allTableData.find(item => item.id == value);
    item ? item : null;
    if (!item) {
      return;
    }
    this.setState(params => ({
      form: {
        ...params.form,
        name: item.name ? item.name : '',
        cerSysteminitImportInfoId: value,
        sfz: item.sfz ? item.sfz : '',
        phone: item.phone ? item.phone : '',
      },
    }));
  };

  sfzChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sfz: value,
      },
    }));
  };
  phoneChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        phone: value,
      },
    }));
  };
  addressChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        address: value,
      },
    }));
  };
  planTimeChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        planTime: dateString,
      },
    }));
  };
  timeEndChange = (date, dateString) => {
    console.log(date, dateString);
    this.setState(params => ({
      form: {
        ...params.form,
        timeEnd: dateString,
      },
    }));
  };
  statusChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        status: value,
      },
    }));
  };

  showModal = () => {
    this.selById();
    this.listAllTableData();
    this.getCity({ level: 1, parentCode: '1' });
    this.setState({
      visible: true,
    });
  };

  //人员
  listAllTableData = () => {
    this.execHttp('plannedFollowUp/listAllTableData', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 9999,
    }).then(resp => {
      if (resp && resp.success) {
        this.setState({
          allTableData: resp.data.list,
        });
      }
    });
  };

  handleOk = () => {
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        const { form } = this.state;
        this.execHttp('plannedFollowUp/edit', {
          ...form,
        }).then(resp => {
          if (resp && resp.success) {
            message.success(resp.message);
            this.setState({
              visible: false,
            });
            this.props.getDataByPage({});
          }
        });
      } else {
        this.errorMessage('请完善表单后提交');
      }
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      form: {},
    });
  };

  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        } else if (param.level == 4) {
          this.setState({
            townshipIdData: resp.data,
          });
        } else if (param.level == 5) {
          this.setState({
            villageIdData: resp.data,
          });
        }
      }
    });
  };
  /**详情*/
  selById = () => {
    this.execHttp('plannedFollowUp/selById', {
      id: this.props.record.id,
    }).then(resp => {
      if (resp && resp.success) {
        this.setState({
          form: resp.data,
        });
        this.getCity({ level: 2, parentCode: '34' });
        this.getCity({ level: 3, parentCode: resp.data.cityId });
        this.getCity({ level: 4, parentCode: resp.data.districtId });
        this.getCity({ level: 5, parentCode: resp.data.townshipId });
      }
    });
  };

  nameFilterOptionHandle = (input, option) => {
    if (option.props.children) {
      if (option.props.children.indexOf(input) >= 0) {
        return true;
      }
    }
  };

  render() {
    const { visible } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <div>
        <Button type="primary" onClick={this.showModal}>
          修改
        </Button>
        <Modal
          title="修改"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={1200}
        >
          <h3>基本信息</h3>
          <Form {...formItemLayout}>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="所属省份">
                  {getFieldDecorator('provinceId', {
                    initialValue: this.state.form.provinceId,
                    rules: [{ required: true, message: '所属省份必选' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.provinceIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属省份"
                    >
                      {this.state.provinceIdData.map(item => (
                        <Select.Option key={item.code}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="所属城市">
                  {getFieldDecorator('cityId', {
                    initialValue: this.state.form.cityId,
                    rules: [{ required: true, message: '所属城市必选' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.cityIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属城市"
                    >
                      {this.state.cityIdData.map(item => (
                        <Select.Option key={item.code}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="所属区/县">
                  {getFieldDecorator('districtId', {
                    initialValue: this.state.form.districtId,
                    rules: [{ required: true, message: '所属区/县必选' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.districtIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属区/县"
                    >
                      {this.state.districtIdData.map(item => (
                        <Select.Option key={item.code}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="所属乡镇">
                  {getFieldDecorator('townshipId', {
                    initialValue: this.state.form.townshipId,
                    rules: [{ required: true, message: '所属乡镇必选' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.townshipIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属乡镇"
                    >
                      {this.state.townshipIdData.map(item => (
                        <Select.Option key={item.code}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="所属村">
                  {getFieldDecorator('villageId', {
                    initialValue: this.state.form.villageId,
                    rules: [{ required: true, message: '所属村必选' }],
                  })(
                    <Select
                      allowClear
                      onChange={this.villageIdChange}
                      style={{ width: 200 }}
                      placeholder="请选择所属村"
                    >
                      {this.state.villageIdData.map(item => (
                        <Select.Option key={item.code}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="姓名">
                  {getFieldDecorator('name', {
                    initialValue: this.state.form.name,
                    rules: [{ required: true, message: '姓名必选' }],
                  })(
                    <Select
                      onChange={this.nameChange}
                      allowClear
                      showSearch
                      // filterOption={(input, option) =>
                      //     option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      // }
                      filterOption={this.nameFilterOptionHandle}
                      style={{ width: 200 }}
                      placeholder="请选择姓名"
                    >
                      {this.state.allTableData.map(item => (
                        <Select.Option key={item.id}>{item.name}</Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="身份证号码">
                  <Input
                    placeholder="身份证号码"
                    value={this.state.form.sfz}
                    disabled={true}
                    onChange={this.sfzChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="手机号">
                  <Input
                    placeholder="手机号"
                    value={this.state.form.phone}
                    disabled={true}
                    onChange={this.phoneChange}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="住址">
                  {getFieldDecorator('address', {
                    initialValue: this.state.form.address,
                    rules: [{ required: true, message: '住址必填' }],
                  })(
                    <Input
                      placeholder="请输入住址"
                      onChange={this.addressChange}
                      style={{ width: 200 }}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={8}>
                <Form.Item label="计划时间">
                  {getFieldDecorator('planTime', {
                    initialValue:
                      this.state.form.planTime === undefined
                        ? this.state.form.planTime
                        : moment(this.state.form.planTime, 'YYYY-MM-DD HH:mm:ss'),
                    rules: [{ required: true, message: '计划时间必填' }],
                  })(
                    <DatePicker
                      style={{ width: 200 }}
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="请选择计划时间"
                      onChange={this.planTimeChange}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="随访状态">
                  {getFieldDecorator('status', {
                    initialValue: this.state.form.status,
                    rules: [{ required: true, message: '随访状态必选' }],
                  })(<Radio.Group options={this.state.whether} onChange={this.statusChange} />)}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
